package com.xy.manage.action;



import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
import com.xy.common.page.Pagination;
import com.xy.common.util.DictUtils;
import com.xy.common.security.BadCredentialsException;
import com.xy.common.security.UsernameNotFoundException;
import com.xy.common.web.CookieUtils;
import com.xy.common.web.RequestUtils;
import com.xy.core.util.SpringBeanUtils;
import com.xy.core.web.WebErrors;

import com.xy.core.model.Tdictionay;
import com.xy.core.model.TdictionayId;
import com.xy.core.service.TdictionayService;



@Controller
public class TdictionayAction{
	private static final Logger log = LoggerFactory.getLogger(TdictionayAction.class);
	public TdictionayAction() {
	}
 
 
 	/**
	 * 数据字典新增页面
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tdictionayAdd.do")
	public String add(HttpServletRequest request, ModelMap model) {
		Tdictionay d = new Tdictionay();
		d.setId(new TdictionayId());
		model.addAttribute("tdictionay", d);
        setDict(model);
        if("6".equals(request.getParameter("type")))
        	return "surverytypeEdit";
        else
        	return "tdictionayEdit";
	}

	/**
	 * 数据字典新增保存
	 * 
	 * @param tdictionay
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("o_tdictionaySave.do")
	public String save(Tdictionay tdictionay, HttpServletRequest request, ModelMap model) {
//		if (null == tdictionay.getId().getType() || "".equals(tdictionay.getId().getType())) {
//			tdictionay.getId().setType("wg");
//		}
//		if (null == tdictionay.getId().getId() || "".equals(tdictionay.getId().getId())) {
//			Map<Object, String> map = DictUtils.getDictByType("wg");
//			if (null == map || map.size() <= 0) {
//				tdictionay.getId().setId("1001");
//			} else {
//				Object[] os = map.keySet().toArray(new Object[map.keySet().size()]);
//				int id = 0;
//				try {
//					id = getNextId(os);
//					tdictionay.getId().setId(id + "");
//				} catch (Exception e) {
//					return "redirect:v_tdictionayList.do?saveMsg=false";
//				}
//			}
//		}
		if(!save("wg","1001",tdictionay))
			return "redirect:v_tdictionayList.do?saveMsg=false";
		WebErrors errors = validateSave(tdictionay, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		tdictionay = tdictionayService.save(tdictionay);
		List<Tdictionay> l = ((TdictionayService) SpringBeanUtils.getBean("tdictionayService")).getAll();
		DictUtils.init(l);
		return "redirect:v_tdictionayList.do";
	}
	
	private boolean save(String type,String defval,Tdictionay tdictionay){
		if (null == tdictionay.getId().getType() || "".equals(tdictionay.getId().getType())) {
			tdictionay.getId().setType(type);
		}
		if (null == tdictionay.getId().getId() || "".equals(tdictionay.getId().getId())) {
			Map<Object, String> map = DictUtils.getDictByType(type);
			if (null == map || map.size() <= 0) {
				tdictionay.getId().setId(defval);
			} else {
				Object[] os = map.keySet().toArray(new Object[map.keySet().size()]);
				int id = 0;
				try {
					id = getNextId(os);
					tdictionay.getId().setId(id + "");
				} catch (Exception e) {
					return false;
				}
			}
		}
		return true;
	}

	/**
	 * 数据字典删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("o_tdictionayDelete.do")
	public String delete(String type,String id) {
		TdictionayId tid = new TdictionayId(id, type);
		Tdictionay temp = new Tdictionay();
		temp.setId(tid);
		Tdictionay tdictionay = tdictionayService.getTdictionay(toMap(temp)).get(0);
		tdictionayService.remove(tdictionay);
		List<Tdictionay> l = ((TdictionayService) SpringBeanUtils
				.getBean("tdictionayService")).getAll();
		DictUtils.init(l);
		if("6".equals(type))
			return "redirect:v_tdictionayListSurveryType.do";
		else
			return "redirect:v_tdictionayList.do";
	}

	/**
	 * 数据字典编辑页面
	 * 
	 * @param type
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tdictionayEdit.do")
	public String edit(String type,String id, HttpServletRequest request, ModelMap model) {
		TdictionayId tid = new TdictionayId(id, type);
		Tdictionay temp = new Tdictionay();
		temp.setId(tid);
		Tdictionay tdictionay = tdictionayService.getTdictionay(toMap(temp)).get(0);
		model.addAttribute("tdictionay", tdictionay);
      model.addAttribute("actionEdit", request.getParameter("actionEdit"));
        setDict(model);
        if("6".equals(type))
        	return "surverytypeEdit";
        else
        	return "tdictionayEdit";
	}

	/**
	 * 数据字典详情
	 * 
	 * @param type
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tdictionayDetail.do")
	public String detail(String type,String id, HttpServletRequest request, ModelMap model) {
		TdictionayId tid = new TdictionayId(id, type);
		Tdictionay temp = new Tdictionay();
		temp.setId(tid);
		Tdictionay tdictionay = tdictionayService.getTdictionay(toMap(temp)).get(0);
//		Tdictionay tdictionay = tdictionayService.get();
		model.addAttribute("tdictionay", tdictionay);
        setDict(model);
		return "tdictionayView";
	}

	/**
	 * 数据字典查询（分页）(办事指南)
	 * 
	 * @param tdictionay
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tdictionayList.do")
	public String listPage(Tdictionay tdictionay, Integer pageNo,HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		TdictionayId id = new TdictionayId(null,"wg");
		tdictionay.setId(id);
		Pagination pagination = tdictionayService.getTdictionayByPage(toMap(tdictionay), pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		if(null!=request.getParameter("saveMsg")){
			model.addAttribute("saveMsg", "保存失败");
		}
        setDict(model);
		return "tdictionayList";
	}

	/**
	 * 数据字典查询（分页）(民意测评)
	 * 
	 * @param tdictionay
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tdictionayListSurveryType.do")
	public String iistSurveryType(Tdictionay tdictionay, Integer pageNo,HttpServletRequest request, ModelMap model) {
		if (pageNo == null)
			pageNo = 1;
		TdictionayId id = new TdictionayId(null,"6");
		tdictionay.setId(id);
		Pagination pagination = tdictionayService.getTdictionayByPage(toMap(tdictionay), pageNo, CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		if(null!=request.getParameter("saveMsg")){
			model.addAttribute("saveMsg", "保存失败");
		}
        setDict(model);
		return "surverytypeList";
	}
	
	@RequestMapping("o_tdictionaySaveSurveryType.do")
	public String saveSurveryType(Tdictionay tdictionay, HttpServletRequest request, ModelMap model) {
		if(!save("6","1",tdictionay))
			return "redirect:v_tdictionayListSurveryType.do?saveMsg=false";
		WebErrors errors = validateSave(tdictionay, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		tdictionay = tdictionayService.save(tdictionay);
		List<Tdictionay> l = ((TdictionayService) SpringBeanUtils.getBean("tdictionayService")).getAll();
		DictUtils.init(l);
		return "redirect:v_tdictionayListSurveryType.do";
	}
	
	
	
	
	/**
	 * 数据字典查询
	 * 
	 * @param tdictionay
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("v_tdictionayList1.do")
	public String list(Tdictionay tdictionay, HttpServletRequest request, ModelMap model) {
		List<Tdictionay> list = tdictionayService.getTdictionay(toMap(tdictionay));
		model.addAttribute("list", list);
        setDict(model);
		return "tdictionayList";
	}


 	/***
	 * 将页面输入信息转成map
	 * 
	 * @param tdictionay
	 * @return
	 */
	private Map<String, Object> toMap(Tdictionay tdictionay) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (tdictionay.getId().getId() != null ) {
			map.put("id.id", tdictionay.getId().getId());
		}
		if (tdictionay.getId().getType() != null ) {
			map.put("id.type", tdictionay.getId().getType());
		}
//		if (tdictionay.gettype() != null && !tdictionay.gettype().equals("")) {
//			map.put("type", tdictionay.gettype());
//		}
//		if (tdictionay.getname() != null && !tdictionay.getname().equals("")) {
//			map.put("name", tdictionay.getname());
//		}
//		if (tdictionay.getremark() != null && !tdictionay.getremark().equals("")) {
//			map.put("remark", tdictionay.getremark());
//		}
//		if (tdictionay.getsequence() != null && !tdictionay.getsequence().equals("")) {
//			map.put("sequence", tdictionay.getsequence());
//		}
		return map;
	}
   
	/**
	 * 设置页面所需的数据字典
	 * @param model
	 */
	private void setDict(ModelMap model){
		
	}

	/**
	 * 数据校验
	 * @param model
	 */
	private WebErrors validateSave(Tdictionay tdictionay, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		/**if (errors.ifOutOfLength(username, "username", 1, 100)) {
			return errors;
		}  */    
		return errors;
	}
	
	/**
	 * 获取字典的下一个id
	 * @param 字典表的id数组
	 * @return
	 * @throws Exception 
	 */
	private Integer getNextId(Object[] o) throws Exception {
		int i, j = 0;
		Object tem = o[j];
		boolean flag = true;
		for (i = 0; i < o.length - 1; i++) {
			if (!isNum(o[i]) || !isNum(o[i + 1])) {
				throw new Exception("Object数组无法转换为Integer类型");
			}
			if (Integer.valueOf(o[j].toString()) < Integer.valueOf(o[i + 1].toString())) {
				tem = o[i + 1];
				j = i + 1;
			}
		}
		return (Integer.valueOf(tem.toString())) + 1;
	}
	
	/**
	 * 判断是否integer
	 * @param o
	 * @return 
	 */
	private boolean isNum(Object o){
		try {
			Integer.valueOf(o.toString());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

   
      
	@Resource
	private TdictionayService tdictionayService;   
}